package com.lagou.rpc.consumer.processor;

import com.lagou.rpc.consumer.anno.RpcReference;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * 给标记有@RpcReference注解的field实例化代理对象
 */
@Component
public class ReferenceBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //获取bean中的fields
        Field[] declaredFields = bean.getClass().getDeclaredFields();
        //遍历fields，查找被@RpcReference标记的field
        for (Field declaredField : declaredFields) {
            if (!declaredField.isAnnotationPresent(RpcReference.class)){
                continue;
            }
            //创建代理对象
            Object proxy = RpcClientProxy.createProxy(declaredField.getType());
            try {
                //设置暴力访问
                declaredField.setAccessible(true);
                //给declaredField赋值
                declaredField.set(bean, proxy);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return bean;
    }
}
